package com.xy.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWToo {
    public static String key="fengtang";
    public static String Token(Map<String,Object> map){
        Map<String,Object> head = new HashMap<>();
        head.put("alg","Hs256");
        head.put("typ","JWT");

        Date date = new Date();
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.SECOND,7200);
        Date time = instance.getTime();

        String token = JWT.create()
                .withHeader(head)
                .withIssuedAt(date)
                .withExpiresAt(time)
                .withClaim("userinfo",map)
                .sign(Algorithm.HMAC256(key));
        return token;
    }
    //煎药
    public static boolean verify(String token){
        Verification require = JWT.require(Algorithm.HMAC256(key));
        try {
            require.build().verify(token);
            return true;
        }catch (Exception e){
            System.out.println("token失效");
            return false;
        }
    }
    //根据token获取自定义的信息
    public static Map<String,Object> getInfo(String token,String mykey){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(key)).build();
        Claim claim = build.verify(token).getClaim(mykey);
        return claim.asMap();
    }
}
